package com.kefu.call.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.kefu.basic.event.BasicMsgEvent;
import com.kefu.basic.model.BasicMsg;
import com.kefu.call.model.ActivityBaseInfo;
import com.kefu.call.model.ActivityInventoryInfo;
import com.kefu.call.service.ActivityInventoryInfoService;
import com.kefu.call.vo.*;
import com.kefu.common.context.KefuContext;
import com.kefu.common.controller.AbstractBaseController;
import com.kefu.common.exception.BusinessException;
import com.kefu.common.result.Result;
import com.kefu.common.result.ResultGenerator;
import com.kefu.common.vo.BatchVo;
import com.kefu.common.vo.DeleteVo;
import com.kefu.common.vo.DetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Api(tags = "活动清单")
@RestController
@RequestMapping("call/activity/inventory")
public class ActivityInventoryInfoController extends AbstractBaseController {
    @Resource
    private ActivityInventoryInfoService activityInventoryInfoService;

    @PostMapping("/add")
    @ApiOperation(value = "新增活动清单", notes = "新增活动清单")
    public Result<String> add(@Validated @RequestBody ActivityInventoryInfoInsertVo activityInventoryInfoVo) {
    	logger.info("新增活动清单:{}", activityInventoryInfoVo);
    	
    	ActivityInventoryInfo info = activityInventoryInfoVo.convert();
        activityInventoryInfoService.save(info);
        return ResultGenerator.genSuccessResult();
    }
    @PostMapping("/batchAdd")
    @ApiOperation(value = "批量新增活动清单", notes = "新增活动清单")
    public Result<String> batchAdd(@Validated @RequestBody ActivityInventoryInfoInsertBatchVo activityInventoryInfoInsertBatchVo) {
    	logger.info("批量新增活动清单:{}", activityInventoryInfoInsertBatchVo);
    	
    	List<ActivityInventoryInfo> list = activityInventoryInfoInsertBatchVo.convert();
    	activityInventoryInfoService.save(list);
    	return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/delete")
    @ApiOperation(value = "删除活动清单", notes = "删除活动清单")
    public Result<String> delete(@Validated @RequestBody DeleteVo delete) {
    	logger.info("删除活动清单:{}", delete);
    	
    	ActivityInventoryInfoUpdateVo update=new ActivityInventoryInfoUpdateVo();
    	update.setInventoryId(delete.getId());
    	update.setDataStatus(0);
        activityInventoryInfoService.update(update.convert());
        return ResultGenerator.genSuccessResult();
    }
    @PostMapping("/batchDelete")
    @ApiOperation(value = "批量删除活动清单", notes = "批量删除活动清单")
    public Result<Integer> batchDelete(@Validated @RequestBody BatchVo batchVo) {
    	logger.info("批量删除活动清单:{}", batchVo);
    	
    	return ResultGenerator.genSuccessResult(activityInventoryInfoService.batchDelete(batchVo));
    }

    @PostMapping("/update")
    @ApiOperation(value = "修改活动清单", notes = "修改活动清单")
    public Result<String> update(@Validated @RequestBody ActivityInventoryInfoUpdateVo activityInventoryInfoVo) {
    	logger.info("修改活动清单:{}", activityInventoryInfoVo);
    	
    	ActivityInventoryInfo info = activityInventoryInfoVo.convert();
        activityInventoryInfoService.update(info);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/detail")
    @ApiOperation(value = "活动清单详情", notes = "活动清单详情")
    public Result<ActivityInventoryInfo> detail(@Validated @RequestBody DetailVo detail) {

        ActivityInventoryInfo activityInventoryInfo = activityInventoryInfoService.findById(detail.getId());
        return ResultGenerator.genSuccessResult(activityInventoryInfo);
    }

    @PostMapping("/list")
    @ApiOperation(value = "查询活动清单", notes = "查询活动清单")
    public Result<Page<ActivityInventoryInfo>> list(@Validated @RequestBody ActivityInventoryInfoSearchVo search) {
        Page<ActivityInventoryInfo> list = activityInventoryInfoService.listInventory(search);
        return ResultGenerator.genSuccessResult(list);
    }
    
    @PostMapping("/preHandel")
    @Deprecated
    @ApiOperation(value = "活动清单预处理", notes = "此功能已无效" )
    public Result<ActivityInventoryInfo> preHandel(@Validated @RequestBody DetailVo detail) {
    	logger.info("活动清单预处理:{}", detail);
    	
    	ActivityInventoryInfo info =activityInventoryInfoService.preHandel(detail.getId());
        return ResultGenerator.genSuccessResult(info);
        
    }
    @PostMapping("/handle")
    @ApiOperation(value = "处理活动清单", notes = "处理活动清单")
    public Result<String> handle(@Validated @RequestBody ActivityInventoryInfoHandleVo activityInventoryInfoVo) {
    	logger.info("处理活动清单:{}", activityInventoryInfoVo);
    	
    	activityInventoryInfoService.handle(activityInventoryInfoVo);
    	return ResultGenerator.genSuccessResult();
    }
    
    @PostMapping("/assignment")
    @ApiOperation(value = "分配活动清单", notes = "分配活动清单")
    public Result<List<String>> assignment(@Validated @RequestBody ActivityInventoryInfoAssignmentVo assignmentVo) {
    	logger.info("处理活动清单:{}", assignmentVo);
        ActivityInventoryInfoAssignmentVo.AssignmentResultVo result = activityInventoryInfoService.assignment(assignmentVo);
        if (Objects.isNull(result)) {
            throw BusinessException.msg("分配方式异常！");
        }
        List<ActivityInventoryInfo> list = result.getList();
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(v -> {
                BasicMsg basicMsg = BasicMsg
                        .builder()
                        .tenantId(KefuContext.getTid())
                        .createId(KefuContext.getUid())
                        .createTime(DateUtil.current())
                        .keyContent(v.getInventoryId())
                        .msgFrom(10)
                        .readFlag(0)
                        .receiveId(v.getUserId())
                        .msgTitle("拨打分配")
                        .msgContent("您有新的呼叫任务被分配，请及时拨打相关清单，号码["+ v.getCustomerPhone() +"]！")
                        .build();
                publisher.publishEvent(new BasicMsgEvent(basicMsg));
            });
        }
        return ResultGenerator.genSuccessResult(result.getMessage());
    }
    @PostMapping("/recovery")
    @ApiOperation(value = "回收活动清单", notes = "回收活动清单")
    public Result<List<String>> recovery(@Validated @RequestBody ActivityInventoryInfoRecoveryVo recoveryVo) {
    	logger.info("回收活动清单:{}", recoveryVo);
    	
    	List<String> message = activityInventoryInfoService.recovery(recoveryVo);
    	return ResultGenerator.genSuccessResult(message);
    }
    
    @PostMapping("/myInventory")
    @ApiOperation(value = "我的活动任务", notes = "我的活动任务")
    public Result<Page<ActivityBaseInfo>> myInventory(@Validated @RequestBody ActivityInventoryInfoMySearchVo search) {
        return ResultGenerator.genSuccessResult(activityInventoryInfoService.myInventory(search));
    }
    
    @PostMapping("/myInventoryList")
    @ApiOperation(value = "我的任务清单", notes = "我的活动清单")
    public Result<Page<ActivityInventoryInfo>> myInventoryList(@Validated @RequestBody ActivityMyInventoryInfoSearchVo search) {

    	return ResultGenerator.genSuccessResult(activityInventoryInfoService.myInventoryList(search));
    }
    
    @PostMapping("/exportMyInventoryList")
    @ApiOperation(value = "导出我的清单")
    public void exportMyInventoryList(@Validated @RequestBody ActivityMyInventoryInfoSearchVo search, HttpServletResponse response) throws IOException {
    	logger.info("导出我的清单:{}", search);
    	search.setPageNo(1);
    	search.setPageSize(50000);
        List<ActivityInventoryInfo> list = activityInventoryInfoService.search(search).getRecords();
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (ActivityInventoryInfo info : list) {
            Map<String, Object> map = Maps.newLinkedHashMap();
            map.put(msg("客户名称"), info.getCustomerName());
            map.put(msg("客户手机号码"), info.getCustomerPhone());
            map.put(msg("处理状态"), info.getActivityStatus());
            mapList.add(map);
        }
        excelWriter(mapList, response);
    }


    @PostMapping("/myInventoryDetail")
    @ApiOperation(value = "我的活动清单详细信息", notes = "我的活动清单详细信息")
    public Result<ActivityBaseInfo> myInventoryDetail(@Validated @RequestBody DetailVo param) {
        ActivityBaseInfo info = activityInventoryInfoService.myInventoryDetail(param.getId());
        return ResultGenerator.genSuccessResult(info);
    }

    @PostMapping("/importDoc")
    @ApiOperation(value = "导入拨打清单", notes = "导入拨打清单")
    public Result<String> importDoc(MultipartFile file, String activityId) throws IOException {
        if (StrUtil.isBlank(activityId)) {
            throw BusinessException.msg("未选择活动信息");
        }
        activityInventoryInfoService.importDoc(file.getInputStream(), activityId);
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/exportDoc")
    @ApiOperation(value = "导出清单", notes = "根据条件不分页一次性导出，传递导出活动ID")
    public void exportDoc(@Validated @RequestBody ActivityInventoryInfoSearchVo search, HttpServletResponse response) throws IOException {
        if (StrUtil.hasBlank(search.getActivityId())) {
            logger.info("未传参导出活动ID");
            return;
        }
        search.setTenantId(KefuContext.getKefuContext().getTenantId());
        List<ActivityInventoryInfo> list = activityInventoryInfoService.searchList(search);
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (ActivityInventoryInfo info : list) {
            Map<String, Object> map = Maps.newLinkedHashMap();
            map.put(msg("拨打状态"), info.getActivityStatus());
            map.put(msg("客户电话"), info.getCustomerPhone());
            map.put(msg("客户姓名"), info.getCustomerName());
            mapList.add(map);
        }
        excelWriter(mapList, response);
    }

    @PostMapping("/checkInventory")
    @ApiOperation(value = "判断该清单号码是否存在其他活动中", notes = "判断该清单号码是否存在其他活动中")
    public Result<List<ActivityInventoryInfo>> checkInventory(@Validated @RequestBody DetailVo vo) {
        logger.info("判断该清单号码是否存在其他活动中:{}", vo);
        List<ActivityInventoryInfo> list = activityInventoryInfoService.checkInventory(vo.getId());
        return ResultGenerator.genSuccessResult(list);
    }

    @PostMapping("/makeCall")
    @ApiOperation(value = "呼叫", notes = "呼叫")
    public Result<String> makeCall(@Validated @RequestBody DetailVo detailVo) {
        logger.info("呼叫:{}", detailVo);
        activityInventoryInfoService.makeCall(detailVo);
        return ResultGenerator.genSuccessResult();
    }
    @PostMapping("/mergeInventory")
    @ApiOperation(value = "合并清单", notes = "合并清单")
    public Result<String> mergeInventory(@Validated @RequestBody Map<String,Object> vo) {
    	logger.info("合并清单:{}", vo);
    	
    	return ResultGenerator.genSuccessResult(activityInventoryInfoService.mergeInventory(vo));
    }
}
